import datetime
import os
import time

import requests
import pandas as pd

# base_url = "https://zhuisuapi.vdvq.com"  # 测试环境
base_url = "https://zhuisu.vdvq.com"  # 正式环境

caigou_url = f"{base_url}/api/purchase_orders/"
re_cg_url = f"{base_url}/api/purchase_return_orders/"
product_url = f"{base_url}/api/goods/?search=&page=1&page_size=16"
login_url = f"{base_url}/api/user/get_token/"

header = {
    "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzMzNjQwMDQ3LCJpYXQiOjE3MzI3NzYwNDcsImp0aSI6IjlkZjMzYzY3OWZhNTQ2ZjE4NThmNGU4MGVlOGVhMmM3IiwidXNlcl9pZCI6NTB9.yBahCpyExlXCveIBDdgkl2WMcbPc3kVW3H-JUKL4vWA"}


def login():
    param = {"password": "Dashan@321", "username": "Modao"}
    resp = requests.post(url=login_url, json=param)
    if str(resp.status_code).startswith("20"):
        access = resp.json().get("access")
        header["authorization"] = f"Bearer {access}"


# 读取Excel文件
def read_excel(ex_name):
    data = pd.read_excel(ex_name, sheet_name=0)
    # 显示数据
    # print(data)
    return data


# 发送采购订单
def send_cg_order(n, supplier, goods, purchase_quantity, handler, purchase_price, warehouse, handle_time):
    # num = str(n).zfill(4)
    num = "000" + str(n)
    number = "CG" + str(datetime.datetime.now().date()).replace("-", "") + num  # 编号
    # supplier = 51  # 供应商
    # goods = 860  # 商品id 858是168粉
    # purchase_quantity = 2.5  # 商品数量
    # handler = 50  # 经手人

    # handle_time = str(datetime.datetime.now().date())  # 处理日期
    purchase_price = purchase_price

    caigou = {"other_amount": 0, "number": number, "supplier": supplier, "warehouse": warehouse, "handler": handler,
              "handle_time": handle_time, "purchase_account_items": [],
              "purchase_goods_items": [
                  {"goods": goods, "purchase_quantity": purchase_quantity, "purchase_price": purchase_price}]}

    resp = requests.post(url=caigou_url, json=caigou, headers=header)
    return resp


# 退采购订单
def re_cg_order(n, purchase_order, goods_id, return_quantity, return_price, handler, warehouse):
    num = str(n).zfill(5)
    # num = "000" + str(n)
    number = "CR" + str(datetime.datetime.now().date()).replace("-", "") + num  # 编号
    # supplier = 51  # 供应商
    # goods = 860  # 商品id 858是168粉
    # purchase_quantity = 2.5  # 商品数量
    # handler = 50  # 经手人
    handle_time = str(datetime.datetime.now().date())  # 处理日期
    purchase_order = purchase_order  # 退货对应的采购订单id

    re_cg = {"other_amount": 0, "number": number, "purchase_order": purchase_order, "supplier": 51,
             "warehouse": warehouse,
             "handler": handler,
             "handle_time": handle_time, "purchase_return_account_items": [],
             "purchase_return_goods_items": [
                 {"purchase_goods": purchase_order, "goods": goods_id, "return_quantity": return_quantity,
                  "return_price": return_price}]}

    resp = requests.post(url=re_cg_url, json=re_cg, headers=header)
    return resp


# 获取产品列表
def get_product():
    resp2 = requests.get(url=product_url, headers=header)
    return resp2.json().get("results")


if __name__ == '__main__':
    # login()

    # resp = get_product()

    # goods_map = {"香雪手抓饼用小麦粉168#-25kg": 858, "麦纯273-25kg": 860, "香雪包子馒头粉35-25kg": 861}
    # goods_map = {i.get("name"): i.get("id") for i in resp}

    path = os.getcwd()
    dirs = os.listdir(path)
    file_name = ""
    for d in dirs:
        if d.startswith("caigou"):
            file_name = d
    if not file_name:
        print("没有找到caigou开头的文件")
        time.sleep(5)
        exit(-1)

    re_data = read_excel(ex_name=file_name)

    ji = int(time.time() * 10) % 1000000
    # 遍历每一行
    for index, row in re_data.iterrows():
        try:
            ji += 1
            print(f"Index: {index}")
            # 你可以访问特定列的数据，例如：
            handle_time1 = row["交货凭证日期"]
            # tmp_time = datetime.datetime.strptime(handle_time1, "%Y/%m/%d")
            handle_time1 = datetime.datetime.strftime(handle_time1, "%Y-%m-%d")
            good_name = row['销售订单项目短文本']  # 858
            good1 = goods_map[good_name]  # 858是粮岛168粉
            quantity1 = row['交货数量（吨）']
            price = row['结算含税单价（元/吨）']
            supplier1 = 51  # 海宁
            handler1 = 50  # dashan
            if quantity1 < 0:  # 退货
                pass  # 因为需要对应的采购订单
                # res3 = re_cg_order(n=ji, purchase_order=66, goods_id=good1, return_quantity=quantity1, return_price=price, handler=50,
                #                    warehouse=40)
                # print(res3.text)

            else:
                resp2 = send_cg_order(n=ji, supplier=supplier1, goods=good1, purchase_quantity=quantity1,
                                      handler=handler1,
                                      purchase_price=price, warehouse=40, handle_time=handle_time1)
                print(resp2.text)
        except Exception as e:
            print("报错：", str(e))
            time.sleep(5)

    print("已完成！")
    time.sleep(5)
# "purchase_account_items": [{"payment_amount": 0, "account": None}],
